# -*- coding: utf-8 -*-
"""
跨平台matplotlib中文字体配置
"""

import os
import platform
import warnings

import matplotlib
from loguru import logger
from matplotlib.font_manager import FontProperties, findfont

# 抑制matplotlib字体相关警告
warnings.filterwarnings('ignore', category=UserWarning, module='matplotlib')
matplotlib.set_loglevel('ERROR')  # 只显示错误级别的日志


def setup_chinese_font():
    """
    配置matplotlib中文字体，支持Windows、Linux、macOS
    """
    system = platform.system()

    # 不同系统的字体配置
    if system == 'Windows':
        font_list = [
            'Microsoft YaHei',
            'SimHei',
            'KaiTi',
            'FangSong',
            'STSong',
            'SimSun',
            'DejaVu Sans'
        ]
    elif system == 'Darwin':  # macOS
        font_list = [
            'PingFang SC',
            'Hiragino Sans GB',
            'STHeiti Light',
            'STHeiti',
            'Arial Unicode MS',
            'Heiti TC',
            'STSong',
            'DejaVu Sans'
        ]
    else:  # Linux
        font_list = [
            'WenQuanYi Micro Hei',
            'WenQuanYi Zen Hei',
            'Noto Sans CJK SC',
            'Noto Sans CJK TC',
            'Source Han Sans SC',
            'DejaVu Sans',
            'Liberation Sans'
        ]

    # 查找真正可用的字体
    available_font = None
    for font_name in font_list:
        try:
            # 测试字体是否真的可用
            font_prop = FontProperties(family=font_name)
            font_path = findfont(font_prop)

            # 检查是否真的找到了指定字体（而不是fallback）
            if font_path and os.path.exists(font_path):
                # 进一步验证字体名称
                if font_name.lower() in os.path.basename(font_path).lower() or font_name == 'DejaVu Sans':
                    available_font = font_name
                    logger.info(f"找到可用字体: {font_name}")
                    break
        except Exception:
            continue

    if available_font:
        # 设置matplotlib字体配置
        matplotlib.rcParams['font.sans-serif'] = [available_font]
        matplotlib.rcParams['axes.unicode_minus'] = False
        matplotlib.rcParams['font.size'] = 10
        matplotlib.rcParams['font.family'] = 'sans-serif'

        # 清除字体缓存
        try:
            matplotlib.font_manager.fontManager.__init__()
        except AttributeError:
            pass

        logger.success(f"成功配置字体: {available_font}")
        return available_font
    else:
        # 使用最基本的配置
        matplotlib.rcParams['font.sans-serif'] = ['DejaVu Sans']
        matplotlib.rcParams['axes.unicode_minus'] = False
        logger.warning("使用默认字体配置")
        return 'DejaVu Sans'

# 移除自动调用
# setup_chinese_font()
